<template>
    <div>
        <div style="display: flex;">
        	
            <div style="margin-right:20px;">
                
        		<el-button @click="newAdd" size="mini" type="primary">新增</el-button>
        		<el-button @click="delOrder()"   
					:disabled="!isDelete"
					size="mini" type="primary">删除</el-button>
        		<el-button  @click="saveGoods" 
					:loading="loading_btn"
					size="mini" type="primary">保存</el-button>
        		<el-button  size="mini" @click="prevNextBtn(2,1)" type="primary">上一条</el-button>
        		<el-button   size="mini" @click="prevNextBtn(2,2)" type="primary">下一条</el-button>
        		
            </div>
        	<div style="margin-top: 2px;">
        		<el-checkbox v-model="orderChecked" 
					:disabled="order=='new'"
					border size="mini">保存后新增</el-checkbox>
        	</div>
        </div>
        <br>
        <div class="searchForm">
			<div >
			    单号： 
				<el-input size="small" v-model="order"
				placeholder="请输入单号" disabled
				style="width:150px;"></el-input>
			</div>
            <div>
                日期： 
				<el-date-picker
				      size="small"
					  :disabled="!isDelete || isUpdateOrderDate!=1"
				      v-model="form.buyer_date"
					  value-format="yyyy-MM-dd"
				      type="date"
				      placeholder="选择日期时间">
				    </el-date-picker>
            </div>
            <div>
                制单人： 
				<el-input size="small" v-model="form.buyer_person" 
				disabled
				placeholder="请输入制单人"  
				style="width:150px;"></el-input>
            </div>
            <div>
                <div style="display: flex;">
                	<div>
                		客户：
                	</div>
                	<div v-if="isDelete">
                		<selectCustomer 
						 holder="请输入客户名称"
						 :supp="form.supplier"
						 @getCustomerName="getCustomerName" />
                	</div>
					<div v-else>
						<el-input size="small" v-model="form.supplier"
						placeholder="请输入供应商" disabled
						style="width:150px;"></el-input>
					</div>
                </div>
            </div>
			<div>
				 <!-- @change="chagenCode" -->
			    串号： <el-input size="small"
				@keyup.enter.native="chagenCode"
				v-model="goods_code" 
				:disabled="!isDelete || changeDis"
			    ref="goods_code"
				placeholder="请扫描串号"  
				style="width:300px;"></el-input>
			</div>
        </div>
        <div style="margin: 15px 0;">
        	<el-button  @click="addBtn"  size="mini" type="warning">增加行</el-button>
        	<!-- <el-button  @click="delRow"  size="mini" type="warning">删除行</el-button> -->
        	<el-button @click="delLastList"  size="mini" type="warning">删除后行</el-button>
        	<!-- <el-button @click="copyRow"  size="mini" type="warning">复制行</el-button> -->
			<el-button @click="showPointe"  size="mini" type="warning">打印</el-button>
		</div>
        <el-table  :data="list"  
			 border  
			>
			
			<!-- <el-table-column
			      type="selection"
			      width="55">
			    </el-table-column> -->
			<!-- <el-table-column   align="center"  width="200px"   label="串号">
				<template slot-scope="scope">
				   <div>
				   	  <el-input @change="changeCodeInput(scope)"  size="mini" v-model="scope.row.code"></el-input>
				   </div>
				</template>
			</el-table-column> -->	
			<el-table-column  label="操作" width="80"   align="center">
			      <template slot-scope="scope">
			          <i class="el-icon-delete" 
						v-if="scope.row.is_disabld!=1"
						style="cursor: pointer;" 
								@click="delRow(scope)"></i>
					  <i v-if="scope.row.is_disabld==1">--</i>
			      </template>
			  </el-table-column>
			<el-table-column   align="center"  width="80"
				label="序号">
				<template slot-scope="scope">
				   <div>
						{{scope.$index+1}}
				   </div>
				</template>
			</el-table-column>
            <el-table-column   align="center"  width="500px"   
				label="商品名称">
				<template slot-scope="scope">
				   <div v-if="!scope.row.id">
						<selectGoods  v-if="isShowSelectGoods" 
							:scopeData="scope" 
							@getGoodsData="getGoodsData" />
				   </div>
				   <div v-else>
					   <el-input size="mini" 
						disabled
						v-model="scope.row.goods_name"></el-input>
				   </div>
				   
				</template>
			</el-table-column>
            <el-table-column  align="center" width="130px"  label="数量">
				<template slot-scope="scope">
				   <div>
						<el-input  @input="cumpMoney(scope)"
							:disabled="scope.row.id"
							size="mini" v-model="scope.row.goods_number"></el-input>
				   </div>
				</template>
			</el-table-column>
			
             <el-table-column   align="center"     
				label="单价">
				<template slot-scope="scope">
				   <div>
						<el-input @input="cumpMoney(scope)" 
							:disabled="scope.row.is_disabld==1"
							size="mini" v-model="scope.row.price"></el-input>
				   </div>
				</template>
			</el-table-column>
            <el-table-column   align="center"  width="130px"   label="金额">
				<template slot-scope="scope">
				   <div>
						<el-input disabled size="mini" v-model="scope.row.money"></el-input>
				   </div>
				</template>
			</el-table-column>
			<el-table-column  align="center" width="130px"  label="库存">
				<template slot-scope="scope">
				   <div>
						<el-input disabled  size="mini" v-model="scope.row.inventory"></el-input>
				   </div>
				</template>
			</el-table-column>
			<el-table-column   align="center"  width="180px"   label="备注">
				<template slot-scope="scope">
				   <div>
						<el-input  size="mini"
							:disabled="scope.row.is_disabld==1"
							v-model="scope.row.remark"></el-input>
				   </div>
				</template>
			</el-table-column>
			<el-table-column   align="center"  width="260px"   label="串号">
				<template slot-scope="scope">
				   <div style="display: flex;">
						<!-- <el-button type="text" @click="look(scope)">查看串号</el-button> -->
						<!-- <div>
							<el-popover
							  placement="left"
							  width="300"
							  trigger="click">
							  <div>
								  <div style="display: flex;">
									  <div style="width: 80px;text-align: right;">
									  	  商品名称：
									  </div>
									  <div>
										  {{scope.row.goods_name}}
									  </div>
								  </div>
								  <div style="display: flex;">
									  <div style="width: 80px;text-align: right;">
										  串号：
									  </div>
									  <div>
										  <div v-for="(el,i) in scope.row.codeArray" :key="i">
											  {{el}}
										  </div>
									  </div>
								  </div>
							  </div>
							  <el-button slot="reference" size="mini" type="primary">
									串号
							  </el-button>
							</el-popover>
						</div> -->
						<div>
							<!-- :disabled="scope.row.is_disabld==1" -->
							<el-button slot="reference" 
								@click="showCode(scope)" size="mini" type="primary">
								串号
							</el-button>
						</div>
						<div style="margin: 0 10px;">
							<el-button slot="reference" 
								:disabled="scope.row.is_disabld==1"
								@click="autoGetCode(scope)" size="mini">
								串号自动获取
							</el-button>
						</div>
						<div style="margin-top: 5px;">
							{{scope.row.codeArray.length}}/{{scope.row.goods_number}}
						</div>
				   </div>
				</template>
			</el-table-column>
			<el-table-column   align="center"
				v-if="order!='new'"
				label="状态">
				<template slot-scope="scope">
				   <div>
					   {{scope.row.is_settle_accounts}}
						<div v-if="scope.row.is_settle_accounts_put==0">
						  <el-tag 
							  size="mini"
							  type="danger"
							  effect="dark">
							 {{scope.row.is_return==1?'已退款':'未收款'}}
							 
						  </el-tag>
						</div>
						<div v-if="scope.row.is_settle_accounts_put==1">
							<el-tag
							   size="mini"
							   effect="dark">
								已收款
							</el-tag> 
						</div>	
				   </div>
				</template>
			</el-table-column>
			<el-table-column   align="center"  label="收款单号" 
				v-if="order!='new'"
				>
				<template slot-scope="scope">
				   <div class="button_text" @click="toPayInfo(scope.row)" 
					v-if="scope.row.pay_order_number">
						{{$utils.sliceStr(scope.row.pay_order_number,6)}}
				   </div>
				</template>
			</el-table-column>
        </el-table>
		<div style="display: flex;margin-top: 10px;">
		  <div style="margin-right: 10px;">
			  数量合计：
		       <el-input size="mini" v-model="sumCountTotaled" 
			   disabled
		      style="width:150px;"></el-input>  
		  </div>
		  <div>
			  金额合计：
		      <el-input size="mini" v-model="sumMoneyTotaled" 
			  disabled
		      style="width:150px;"></el-input>
		  </div>
		</div>
		<el-dialog
		  title="查看串号"
		  :close-on-click-modal="false"
		  :visible.sync="isShow"
		  width="500px">
		  <scanCode :ttype="type" :rowData="rowData"
		    :list1="list"
			@getCode="getCode" v-if="isShow" />
		</el-dialog>
		<el-dialog
		  title="打印"
		  :close-on-click-modal="false"
		  :visible.sync="isShowPointe"
		  width="770px">
		  <div>
			  <div id="print_demo">
				  <div style="text-align: center;font-size:16px">
					  郑州踏浪出库单A1-06
				  </div>
				  <br />
				  <div class="flex flex_b">
				  	<div class="flex">
				  		<div class="name">日期：</div>
				  		<div>{{form.buyer_date}}</div>
				  	</div>
				  	<div class="flex">
				  		<div>打印时间：</div>
				  		<div>{{$utils.formatNowDate()}}</div>
				  	</div>
				  	<div class="flex">
				  		<div>客户：</div>
				  		<div>{{form.supplier}}</div>
				  	</div>
				  </div>
				  <br>
				  <!-- <el-table  :data="list"
				  	 border  
				  	>
				  	<el-table-column   align="center"  width="80"
				  		label="序号">
				  		<template slot-scope="scope">
				  		   <div>
				  				{{scope.$index+1}}
				  		   </div>
				  		</template>
				  	</el-table-column>
				  	<el-table-column   align="center"  width="320px"
				  		label="商品名称" prop="goods_name" />
				  				<el-table-column   align="center"  
				  					label="数量" prop="goods_number" />
				  				<el-table-column   align="center"  
				  					label="单价" prop="price" />
				  				<el-table-column   align="center" 
				  					label="金额" prop="money" />	
				  </el-table> -->
				  <div style="text-align: center;border-bottom: 1px solid #000;">
					  <div class="flex">
						  <div class="td1 bor-r-no">
							  序号
						  </div>
						  <div class="td2 bor-r-no">
							  商品名称
						  </div>
						  <div class="td1 bor-r-no">
							  数量
						  </div>
						  <div class="td1 bor-r-no">
							  单价
						  </div>
						  <div class="td1">
							  金额
						  </div>
					  </div>
					  <div class="flex" v-for="(el,i) in list">
						  <div class="td1 bor-r-no">
						  		{{i+1}}
						  </div>
						  <div class="td2 bor-r-no">
						  		{{el.goods_name}}
						  </div>
						  <div class="td1 bor-r-no">
						  		{{el.goods_number}}
						  </div>
						  <div class="td1 bor-r-no">
						  		{{el.price}}
						  </div>
						  <div class="td1">
						  		{{el.money}}
						  </div>
					  </div>
				  </div>
				  <div style="display: flex;margin-top: 10px;">
				    <div style="margin-right: 150px;">
				  	  数量合计：{{sumCountTotaled}}
				    </div>
				    <div>
				  	  金额合计：{{sumMoneyTotaled}}
				    </div>
				  </div>
			  </div>
			  <br>
			  <div style="text-align: right;">
				  <el-button 
					v-print="printObj"
					size="mini"
					type="primary">确定打印</el-button>
			  </div>
		  </div>
		</el-dialog>
		
    </div>
</template>
<script>
	import selectGoods from "./components/newSelectGoods"
	import selectCustomer from "@/components/selectCustomer"
	import scanCode from "@/components/scanCode"
    export default {
        components:{
			selectCustomer,selectGoods,scanCode
        },

        data(){
            return {
				isShowPointe:false,
				goods_code:'',
                form:{
                    buyer_date:"",
					buyer_person:"",
					supplier:"",
					logistics_number:""
                },
				supperData:[],
				rowData:{},
				isShow:false,
				index:0,
				isShowSelectGoods:true,
				order_number:"",
				type:2,
				isUpdateOrderDate:1,
				changeDis:false,
				printObj:{
					id: "print_demo",
					popTitle: '',
					extraCss: '',
					extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>'
			    },
            }
        },
		beforeRouteEnter(to,from,next){
			let bool = false
			if(from.path=='/wholesalerSys/wholesalerDay'){
				bool = true
			}
			if(from.path=='/profitCalculation/profitCalculationInfo'){
				bool = true
			}
			if(bool){
				to.meta.keepAlive = false
			}else{
				to.meta.keepAlive = true
			}
			next()
		},
		mounted(){
			this.initView()
			this.isUpdateOrderDate = sessionStorage.getItem('isUpdateOrderDate')
			window.addEventListener('keyup', this.handleKeyDown);
		},
		beforeUnmount() {
		    window.removeEventListener('keyup', this.handleKeyDown);
		  },
	   beforeRouteLeave(to,from,next){
		 this.$notify.closeAll()
		 next()
	   },
        methods:{
			showPointe(){
				this.list = this.list.filter((item)=>{
					return item.goods_name
				})
				this.isShowPointe = true
			},
			toPayInfo(row){
				this.$router.push({
					path:'/settlementSys/putAmount',
					query:{
						order_number:row.pay_order_number
					}
				})
			},
			handleKeyDown(event){
				// event 中有altKey 是一个bool值
				if(event.key=='s' && event.altKey){
					this.saveGoods()
				}
			},
			initView(){
				this.list = []
				this.form.buyer_date = this.$utils.formatNowDate(2)
				this.form.buyer_person = sessionStorage.getItem('user_name')
				document.title = '快速批发'
				this.$refs.goods_code.focus()
				let order_number = this.$route.query.order_number
				if(order_number){
					this.order_number = order_number
					this.initData(order_number)
				}else{
					this.addBtn()
				}
			},
			initData(order_number){
				this.$post('/buyerSys/getBuyerForOrder',{order_number,type:2},res=>{
					let result = res.data
					if(result.data.length){
						this.form.buyer_date = result.data[0].buyer_date
						this.form.buyer_person = result.data[0].buyer_person
						this.form.supplier = result.data[0].supplier
						this.form.logistics_number = result.data[0].logistics_number
						
						for(let item of result.data){
							let obj = {
								id:item.id,
								goods_name:item.goods_name,
								goods_number:item.goods_number,
								price:item.sales_price,
								money:item.sales_price*item.goods_number,
								remark:item.remark,
								order_number:item.order_number,
								inventory:0,
								is_disabld:item.is_disabld,
								pay_order_number:item.pay_order_number,
								is_settle_accounts_put:item.is_settle_accounts_put,
								is_return:item.is_return
							}
							if(item.is_disabld == 1) this.isDelete=false
							if(item.code_arr){
								obj.codeArray = JSON.parse(item.code_arr)
							}else{
								obj.codeArray = [item.code]
							}
							this.list.unshift(obj)
						}
						this.getStore()
					}
				})
			},
			autoGetCode(scope){
				var codes = []
				for(let item of this.list){
					if(item.codeArray){
						codes.push(...item.codeArray)
					}
				}
				let index = scope.$index
				let goods_name = scope.row.goods_name
				let goods_number = scope.row.goods_number
			    if(this.$route.query.order_number){
					goods_number = goods_number - this.list[index].codeArray.length
				}
				if(goods_number<=0) return
				
				let params = {
					goods_name:goods_name,
					goods_number:goods_number,
				}
				
				if(codes.length){
					params.codes = codes
				}
				
				this.$post('/buyerSys/autoGetCode',params,res=>{
					let result = res.data.data
					if(result){
						let arr = result.map(item=>{
							return item.code
						})
						
						if(this.$route.query.order_number){
							this.list[index].codeArray.push(...arr)
						}else{
							this.list[index].codeArray = arr
						}
						
					}
				})
			},
			getCode(val){
				this.list[this.index].codeArray = [...val]
				let goods_number = this.list[this.index].goods_number
				if(goods_number == val.length){
					this.isShow = false
				}
			},
			showCode(scope){
				this.isShow = true
				this.rowData = scope.row
				this.index = scope.$index
			},
			chagenCode(){
		      
				
				this.goods_code = this.goods_code.replace(/ /g,'')
				let params = {
					code:this.goods_code
				}
				this.changeDis = true
				
				this.$post('/buyerSys/getGoodsForCode',params,res=>{
					let result = res.data.data
					this.changeDis = false
					setTimeout(()=>{
						this.$refs.goods_code.focus()
					},1)
					if(result){
						
						let obj = {
							id:undefined,
							goods_name:result.goods_name,
							goods_number:1,
							price:'',
							money:'',
							code:'',
							remark:result.remark,
							codeArray:[],
							inventory:1
						}
						if(this.list.length==0 || this.order!='new'){
							this.list.push(obj)
						}else{
							var isPush = true
							for(let item of this.list){
								if(item.goods_name == result.goods_name){
									let bool = item.codeArray.filter((ele)=> { 
										return ele.toUpperCase() == this.goods_code.toUpperCase() }).length == 0
									if(bool){
										item.goods_number++
										item.codeArray.push(result.code)
									}else{
										this.$message.error('该商品已经存在')
									}
									// item.codeArray.push(this.goods_code)
									isPush = false
								}else if(item.goods_name=='' && this.list.length==1){
									this.list = []
									obj.codeArray.push(this.goods_code)
									setTimeout(()=>{
										this.list.push(obj)
									},200)
									isPush = false
								}
							}
							if(isPush){
								obj.codeArray.push(this.goods_code)
								this.list.push(obj)
							}
						}
						this.goods_code = ''
					}else{
						this.goods_code = ''
						this.$message.error('串号不在库存中')
					}
					
					setTimeout(()=>{
						this.getStore()
					},300)
				})
			},
			cumpMoney(scope){
				let index = scope.$index
				let goods_number = scope.row.goods_number
				let price = scope.row.price
				if(goods_number && price){
					this.list[index].money = goods_number * price
				}else{
					this.list[index].money = 0
				}
				// if(goods_number){
				// 	this.list[index].codeArray.length = goods_number
				// }
			},
			getCustomerName(val){
				this.form.supplier = val
			},
			getStore(){
				// for(let i in this.list){
				// 	let params = {
				// 		goods_name:this.list[i].goods_name
				// 	}
				// 	this.$post('/buyerSys/getGoodsForName',params,res=>{
				// 		let result = res.data.data
				// 		if(result.length>0){
				// 			this.list[i].inventory = result.length
				// 		}
				// 	})
				// }
				
				let arr = this.list.map((el)=>{
					return {
						id:el.id,
						goods_name:el.goods_name,
						cid:sessionStorage.getItem('cid')
					}
				})
				this.$notify.closeAll()
				this.$post('/buyerSys/getGoodsInventory',arr,res=>{
					let result = res.data.data
					// if(result.length>0){
					// 	this.list[i].inventory = result.length
					// }
					for(let i in this.list){
						this.list[i].inventory = result[i].inventory
					}
					for(let item of result){
						let index = item.children.findIndex(el=>{
							return el.remark
						})
						// item.children = item.children.filter(el=>{
						// 	return el.remark
						// })
						let html = ''
						if(index>-1){
							for(let ele of item.children){
								html+=`<div >
										<div class="flex">
											<div style="width: 40px;text-align: right;">
											  串号：
											</div>
											<div style="width: 200px;">
												${ele.code}
											</div>
										</div>
										<div class="flex" style="color:red">
											<div style="width: 40px;text-align: right;">
											  备注：
											</div>
											<div style="width: 200px;">
												${ele.remark}
											</div>
										</div>
									</div>`
							}
						}
						
						if(html){
							setTimeout(()=>{
								this.$notify({
									 title: item.goods_name,
									 dangerouslyUseHTMLString:true,
									 message: html,
									 duration: 0
								   });
							},100)
							
						}
					}
					
				})
			},
			getGoodsData(val){
				let index = val.rowIndex
				let goods_name = val.goods_name
				this.list[index].goods_name = goods_name
				let len = this.list.length
				if(len-1 == index){
					this.addBtn()
				}
				this.$post('/buyerSys/getGoodsForName',{goods_name},res=>{
					let result = res.data.data
					if(result.length==1){ //只有一个
						this.list[index].goods_number = 1
						// this.list[index].codeArray = [result[0].code]
						// this.list[index].money = result[0].money
						this.list[index].inventory = 1
					}else if(result.length>1){ //有多个
						let codeArray = []
						// for(let item of result){
						// 	codeArray.push(item.code)
						// }
						this.list[index].goods_number = 1
						this.list[index].inventory = result.length
						// this.list[index].money = result[0].price * result.length
						this.list[index].codeArray = codeArray
					}
					if(result.length){
						this.list[index].goods_name = result[0].goods_name
						// this.list[index].price = result[0].price
						// this.form.supplier= result[0].supplier
					}
					
					// 1显示串号 2保存的时候把多个分开 3删除串号的时候减少数量
					
					// if(result.data){
					// 	if(result.data.id){
					// 		this.list[index].goods_name = result.data.goods_name
					// 		this.list[index].goods_number = 1
					// 		this.list[index].price = result.data.price
					// 		this.list[index].money = result.data.money
					// 		this.form.supplier= result.data.supplier
							
					// 	}
					// }
					console.log(this.list,1111111)
				})
				
			},
            saveGoods(){
				let order_number = this.$utils.generateRandomString(2)
				
				let len = this.list.length
				if(len==0) return this.$message.error('请添加批发商品')
				if(!this.list[len-1].goods_name){
					this.delLastList()
				}
				
				if(!this.form.supplier) return this.$message.error('请输入客户')
				let cid = sessionStorage.getItem('cid')
				for(let item of this.list){
					item.cid = cid
					if(this.$route.query.order_number){
						item.order_number = this.$route.query.order_number
						item.update_person = sessionStorage.getItem('user_name')
					}else{
						item.order_number = order_number
					}
					if(!item.goods_name) return this.$message.error('商品名称不能为空')
					if(item.codeArray.length != item.goods_number){
						return this.$message.error('商品串号预与商品数量不一致')
					}
					item.buyer_date = this.form.buyer_date
					item.buyer_person = this.form.buyer_person
					item.supplier = this.form.supplier
					item.logistics_number = this.form.logistics_number
					item.code_arr = JSON.stringify(item.codeArray)
					item.code_arr_length = item.codeArray.length
					item.type = 2
					
				}
				
				// var arr = []
				
				
				// for(let item of this.list){
				// 	let obj = {}
				// 	for(let i in item){
				// 		obj[i] = item[i]
				// 	}
				// 	obj.codeArray = [item.codeArray[0]]
				// 	arr.push(obj)
				// }
				
				// let newArr = []
				
				
				// arr.forEach((item,i)=>{
				// 	if(item.goods_number>1){
				// 		for(let j=1;j<=item.goods_number-1;j++){
				// 			let obj = {}
				// 			for(let k in item){
				// 				if(k!='codeArray'){
				// 					obj[k] = item[k]
				// 				}
				// 			}
				// 			let code_arr = JSON.parse(item.code_arr)
				// 			obj.codeArray = [code_arr[j]]
				// 			newArr.push(obj)
				// 		}
				// 	}
				// })
				// arr.push(...newArr)
				
				// // arr.sort((a,b)=>{
				// // 	return a.id-b.id
				// // })
				
				// arr.forEach((item,i)=>{
				// 	item.code_arr = JSON.stringify(item.codeArray)
				// 	item.goods_number = 1
				// })
				
				this.loading_btn = true
				this.$post('/buyerSys/addEditBuyer',this.list,res=>{
					let result = res.data
					this.loading_btn = false
					if(result.code == 200){
						// this.list = []
						this.$message.success('操作成功')
						if(this.orderChecked){
							// setTimeout(()=>{
								this.newAdd()
							// },1000)
						}
					}
					
				})
			
				
			},
            addBtn(){ 
                let obj = {
					id:undefined,
                    goods_name:"",
					goods_number:1,
					price:"",
					money:"",
					code:'',
					remark:"",
					codeArray:[],
					inventory:0,
                }
                this.list.push(obj)
            },
        }
    }
</script>
<style lang="scss" scoped>
	.td1{
		width: 110px;padding: 10px;border: 1px solid #000;
		
		border-bottom: none;
	}
	.td2{
		width: 320px;padding: 10px;border: 1px solid #000;
		border-bottom: none;
	}
	.bor-r-no{
		border-right: none;
	}
</style>
